package com.unitd.modules.sso.util;

import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.SSOToken;
import com.unitd.modules.comm.exception.ConfigServerException;
import com.unitd.modules.configcenter.entity.OperateLogs;
import com.unitd.frame.comm.utils.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @desc 权限信息控制
 * @filename SecurityUtil.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2018-01-30
 */
public class SecurityUtil {

	/** 记录日志信息的日志线程持有器 */
	private static ThreadLocal<OperateLogs> operateLogHolder = new ThreadLocal<>();

	/**
	 * @return 当前http请求的用户信息
	 * @desc 获取当前http请求的用户信息
	 */
	public static SSOToken getLoginUserInfo() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return SSOHelper.getToken(request);
	}

	/**
	 * @desc 判断当前用户是否未超级管理员
	 * @return true/false
	 */
	public static boolean isSuperAdmin() {
		SSOToken userInfo = getLoginUserInfo();
		return userInfo != null && userInfo.isSuperAdmin();
	}

	/**
	 * @desc 判断当前请求是否只能时超级管理员的操作权限, 如果是, 则抛出异常信息
	 */
	public static void requireSuperAdmin() {
		if (!isSuperAdmin()) {
			throw new ConfigServerException(403, "超级管理员才有权限操作");
		}
	}

	/**
	 * @desc 判断是否必须需要配置信息的profile信息
	 * @param profile 配置信息
	 */
	public static void requireProfileGanted(String profile) {
		if (StringUtils.isBlank(profile)) throw new ConfigServerException(1001, "profile字段缺失");
		SSOToken userInfo = getLoginUserInfo();
		if (userInfo.isSuperAdmin()) return;
		if (!userInfo.getGantProfiles().contains(profile)) {
			throw new ConfigServerException(403, "你没有profile[" + profile + "]权限");
		}
	}

	/***
	 * @desc 获取当前操作的日志对象
	 * @return 日志对象
	 */
	public static OperateLogs getOperateLog() {
		OperateLogs log = operateLogHolder.get();
		if (log == null) {
			log = new OperateLogs();
			log.setActTime(new Date());
			operateLogHolder.set(log);
		}
		return log;
	}

	/**
	 * @desc 释放当前请求操作的日志线程句柄对象, 完成日志操作
	 */
	public static void clearOperateLogHolder() {
		operateLogHolder.remove();
	}
}